{% extends 'base.html' %}

{% block title %}{{ locker.name }} - 安全消息传递{% endblock %}

{% block content %}
<div class="container">
    <div class="header">
        <h1>{{ locker.name }}</h1>
        <p class="subtitle">容量: {{ locker.get_used_space() }}/{{ locker.capacity }}</p>
    </div>

    <div class="locker-detail-container">
        <div class="locker-status">
            <div class="capacity-bar large">
                <div class="capacity-fill" style="width: {{ (locker.get_used_space() / locker.capacity) * 100 }}%;"></div>
            </div>
            <div class="capacity-text">
                {% if locker.is_full() %}
                <span class="status-full">此消息柜已满</span>
                {% else %}
                <span class="status-available">可用空间: {{ locker.capacity - locker.get_used_space() }}</span>
                {% endif %}
            </div>
        </div>

        <div class="locker-tabs">
            <div class="tab-header">
                <button class="tab-btn active" data-tab="store">存储消息</button>
                <button class="tab-btn" data-tab="retrieve">获取消息</button>
            </div>
            
            <div class="tab-content">
                <div class="tab-pane active" id="store-tab">
                    {% if locker.is_full() %}
                    <div class="message-box error">
                        <i class="fas fa-exclamation-circle"></i>
                        <p>此消息柜已满，请选择其他消息柜</p>
                    </div>
                    {% else %}
                    <form id="store-message-form">
                        <div class="form-group">
                            <label for="message-content">消息内容</label>
                            <textarea id="message-content" name="content" rows="5" placeholder="在这里输入您的消息..." required></textarea>
                        </div>
                        <div class="form-group">
                            <label for="message-password">6位数密码</label>
                            <div class="password-input-group">
                                <input type="password" id="message-password" name="password" 
                                       placeholder="请输入6位数字密码" pattern="[0-9]{6}" required>
                                <button type="button" class="toggle-password">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                            <small>请记住此密码，它将用于获取消息</small>
                        </div>
                        <input type="hidden" name="locker_id" value="{{ locker.id }}">
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-paper-plane"></i> 存储消息
                            </button>
                        </div>
                    </form>
                    {% endif %}
                </div>
                
                <div class="tab-pane" id="retrieve-tab">
                    <form id="retrieve-message-form">
                        <div class="form-group">
                            <label for="retrieve-password">输入6位数密码</label>
                            <div class="password-input-group">
                                <input type="password" id="retrieve-password" name="password" 
                                       placeholder="请输入6位数字密码" pattern="[0-9]{6}" required>
                                <button type="button" class="toggle-password">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        <input type="hidden" name="locker_id" value="{{ locker.id }}">
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-unlock-alt"></i> 获取消息
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 成功存储消息后的结果卡片 -->
        <div class="result-card hidden" id="store-result-card">
            <div class="result-header">
                <h2>消息已成功存储</h2>
            </div>
            <div class="result-content">
                <p>您的消息已成功存储在 <strong id="result-locker-name"></strong></p>
                <p>请记住以下信息以便获取消息：</p>
                <div class="info-item">
                    <span>消息ID：</span>
                    <span id="result-message-id" class="highlight"></span>
                </div>
                <div class="info-item">
                    <span>柜子编号：</span>
                    <span id="result-locker-id" class="highlight"></span>
                </div>
                <div class="info-item">
                    <span>密码：</span>
                    <span class="highlight">您设置的6位数密码</span>
                </div>
            </div>
            <div class="result-actions">
                <button id="store-new-btn" class="btn btn-secondary">
                    <i class="fas fa-plus"></i> 存储新消息
                </button>
                <a href="{{ url_for('lockers') }}" class="btn btn-primary">
                    <i class="fas fa-list"></i> 查看所有消息柜
                </a>
            </div>
        </div>

        <!-- 成功获取消息后的结果卡片 -->
        <div class="message-content-card hidden" id="retrieve-result-card">
            <div class="message-header">
                <h2>消息内容</h2>
                <p>此消息已从 <strong id="retrieved-locker-name"></strong> 中删除</p>
            </div>
            <div class="message-body">
                <pre id="message-content-view"></pre>
            </div>
            <div class="message-actions">
                <button id="copy-message-btn" class="btn btn-secondary">
                    <i class="fas fa-copy"></i> 复制消息
                </button>
                <button id="back-to-locker-btn" class="btn btn-primary">
                    <i class="fas fa-arrow-left"></i> 返回
                </button>
            </div>
        </div>
    </div>

    <div class="back-section">
        <a href="{{ url_for('lockers') }}" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> 返回消息柜列表
        </a>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{{ url_for('static', filename='js/locker.js') }}"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 设置容量条颜色
    const capacityFill = document.querySelector('.capacity-fill');
    const width = parseFloat(capacityFill.style.width);
    if (width >= 90) {
        capacityFill.classList.add('capacity-critical');
    } else if (width >= 70) {
        capacityFill.classList.add('capacity-warning');
    } else {
        capacityFill.classList.add('capacity-good');
    }
    
    // 标签切换
    const tabBtns = document.querySelectorAll('.tab-btn');
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            // 移除所有活动状态
            tabBtns.forEach(b => b.classList.remove('active'));
            document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
            
            // 添加当前活动状态
            btn.classList.add('active');
            const tabId = btn.getAttribute('data-tab') + '-tab';
            document.getElementById(tabId).classList.add('active');
        });
    });
    
    // 密码显示/隐藏
    const toggleButtons = document.querySelectorAll('.toggle-password');
    toggleButtons.forEach(button => {
        button.addEventListener('click', () => {
            const input = button.parentElement.querySelector('input');
            const icon = button.querySelector('i');
            
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
    });
    
    // 存储消息表单提交
    const storeForm = document.getElementById('store-message-form');
    if (storeForm) {
        storeForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const content = document.getElementById('message-content').value;
            const password = document.getElementById('message-password').value;
            const lockerId = storeForm.querySelector('input[name="locker_id"]').value;
            
            // 验证密码
            if (!/^\d{6}$/.test(password)) {
                showError(storeForm, '密码必须是6位数字');
                return;
            }
            
            // 显示加载状态
            const submitBtn = storeForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 存储中...';
            
            try {
                const response = await fetch('/create_in_locker', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        content: content,
                        password: password,
                        locker_id: lockerId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 显示成功信息
                    document.getElementById('result-message-id').textContent = data.message_id;
                    document.getElementById('result-locker-id').textContent = data.locker_id;
                    document.getElementById('result-locker-name').textContent = data.locker_name;
                    
                    // 隐藏表单，显示结果
                    document.querySelector('.locker-tabs').classList.add('hidden');
                    document.getElementById('store-result-card').classList.remove('hidden');
                } else {
                    showError(storeForm, data.error || '存储消息失败，请重试');
                }
            } catch (error) {
                showError(storeForm, '发生错误，请重试');
                console.error('Error:', error);
            } finally {
                // 重置按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            }
        });
    }
    
    // 获取消息表单提交
    const retrieveForm = document.getElementById('retrieve-message-form');
    if (retrieveForm) {
        retrieveForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const password = document.getElementById('retrieve-password').value;
            const lockerId = retrieveForm.querySelector('input[name="locker_id"]').value;
            
            // 验证密码
            if (!/^\d{6}$/.test(password)) {
                showError(retrieveForm, '密码必须是6位数字');
                return;
            }
            
            // 显示加载状态
            const submitBtn = retrieveForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 获取中...';
            
            try {
                const response = await fetch('/retrieve_from_locker', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        locker_id: lockerId,
                        password: password
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 显示消息内容
                    document.getElementById('message-content-view').textContent = data.content;
                    document.getElementById('retrieved-locker-name').textContent = data.locker_name;
                    
                    // 隐藏表单，显示结果
                    document.querySelector('.locker-tabs').classList.add('hidden');
                    document.getElementById('retrieve-result-card').classList.remove('hidden');
                } else {
                    showError(retrieveForm, data.error || '获取消息失败，请检查密码');
                }
            } catch (error) {
                showError(retrieveForm, '发生错误，请重试');
                console.error('Error:', error);
            } finally {
                // 重置按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            }
        });
    }
    
    // 复制消息按钮
    const copyMessageBtn = document.getElementById('copy-message-btn');
    if (copyMessageBtn) {
        copyMessageBtn.addEventListener('click', () => {
            const messageContent = document.getElementById('message-content-view').textContent;
            navigator.clipboard.writeText(messageContent).then(() => {
                const originalText = copyMessageBtn.innerHTML;
                copyMessageBtn.innerHTML = '<i class="fas fa-check"></i> 已复制';
                
                setTimeout(() => {
                    copyMessageBtn.innerHTML = originalText;
                }, 2000);
            });
        });
    }
    
    // 返回按钮
    const backToLockerBtn = document.getElementById('back-to-locker-btn');
    if (backToLockerBtn) {
        backToLockerBtn.addEventListener('click', () => {
            document.getElementById('retrieve-result-card').classList.add('hidden');
            document.querySelector('.locker-tabs').classList.remove('hidden');
            document.getElementById('retrieve-password').value = '';
            // 刷新页面以更新容量
            location.reload();
        });
    }
    
    // 存储新消息按钮
    const storeNewBtn = document.getElementById('store-new-btn');
    if (storeNewBtn) {
        storeNewBtn.addEventListener('click', () => {
            document.getElementById('store-result-card').classList.add('hidden');
            document.querySelector('.locker-tabs').classList.remove('hidden');
            storeForm.reset();
            // 刷新页面以更新容量
            location.reload();
        });
    }
    
    // 显示错误信息
    function showError(form, message) {
        // 检查是否已存在错误元素
        let errorElement = form.querySelector('.error-message');
        
        if (!errorElement) {
            // 创建错误元素
            errorElement = document.createElement('div');
            errorElement.className = 'error-message';
            errorElement.style.color = 'var(--error-color)';
            errorElement.style.padding = '0.75rem';
            errorElement.style.marginTop = '1rem';
            errorElement.style.backgroundColor = 'rgba(245, 34, 45, 0.1)';
            errorElement.style.borderRadius = '0.25rem';
            errorElement.style.borderLeft = '3px solid var(--error-color)';
            
            // 添加到表单
            form.appendChild(errorElement);
        }
        
        // 设置消息
        errorElement.textContent = message;
        
        // 一段时间后移除
        setTimeout(() => {
            errorElement.style.display = 'none';
            setTimeout(() => {
                errorElement.remove();
            }, 300);
        }, 5000);
    }
});
</script>
{% endblock %}
